﻿#include "../../ctlHandle.h"
#include "../../ctlEdit.h"
#include <algorithm>

namespace swui
{
	ctlRoot::lamNotifyEvent createEditInsertLimitHandle(
		const ctlText& limitText,
		bool limitWay, bool copyBehavior)
	{
		typedef std::wstring::value_type wtype;
		ctlText wideText = limitText.toWideString();
		return ctlRoot::lamNotifyEvent(
			[=](ctlRoot* object, ctlNotifyEvent* notify)
		{
			ctlNotifyEdit* editInfo = static_cast<ctlNotifyEdit*>(notify->info);
			if(editInfo->state == ctlNotifyEdit::insert)
			{
				//将插入的字符转换成宽字符
				wtype value = editInfo->text.wc;
				if(object->isUnicode() == false)
				{
					ctlText text(editInfo->text.c);
					value = text.toWideString().getWideString()[0];
				}
				//判断是否允许插入
				if(limitWay == true)
				{
					*editInfo->isAllow = wideText.getStdWideString().find(
						value, 0) != std::wstring::npos;
				} else {
					*editInfo->isAllow = wideText.getStdWideString().find(
						value, 0) == std::wstring::npos;
				}
			} else if(editInfo->state == ctlNotifyEdit::paste) {
				std::wstring& wstr = *editInfo->str;
				const std::wstring& limit = wideText.getStdWideString();	
				if(copyBehavior == false)
				{
					auto firstOf = std::find_first_of(wstr.begin(), wstr.end(), limit.begin(), limit.end());
					if(limitWay == true)
						*editInfo->isAllow = firstOf != wstr.end();
					else *editInfo->isAllow = firstOf == wstr.end();
				} else {
					if(limitWay == false)
					{
						auto firstOf = std::find_first_of(wstr.begin(), wstr.end(), limit.begin(), limit.end());
						while(firstOf != wstr.end())
							firstOf = std::find_first_of(wstr.erase(firstOf), wstr.end(), limit.begin(), limit.end());
					} else {
						std::wstring tempWstr = std::move(wstr);
						auto firstOf = std::find_first_of(tempWstr.begin(), tempWstr.end(), limit.begin(), limit.end());
						while(firstOf != tempWstr.end())
						{
							wstr.push_back(*firstOf++);
							firstOf = std::find_first_of(firstOf, tempWstr.end(), limit.begin(), limit.end());
						}
					}
				}
			}
		} );
	}
}